  

import _ from 'lodash'
import { h, ref, reactive } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
import { useAsyncState } from '@vueuse/core'
import { useTextCopy } from '../components/dag/use-text-copy'
import {
  batchCopyByCodes,
  batchDeleteByCodes,
  batchExportByCodes,
  deleteByCode,
  queryListPagingReq,
  release
} from '@/service/modules/process-definition'
import TableAction from './components/table-action'
import styles from './index.module.scss'
import { NTag, NSpace, NIcon, NButton, NEllipsis,NTooltip } from 'naive-ui'
import { CopyOutlined } from '@vicons/antd'
import ButtonLink from '@/components/button-link'
import {
  COLUMN_WIDTH_CONFIG,
  calculateTableWidth,
  DefaultTableWidth
} from '@/common/column-width-config'
import type { IDefinitionParam } from './types'
import type { Router } from 'vue-router'
import type { TableColumns, RowKey } from 'naive-ui/es/data-table/src/interface'
import { EditOutlined } from '@vicons/antd'

export function useTable() {
  const { t } = useI18n()
  const router: Router = useRouter()
  const { copy } = useTextCopy()
  const variables = reactive({
    columns: [],
    tableWidth: DefaultTableWidth,
    checkedRowKeys: [] as Array<RowKey>,
    row: {},
    tableData: [],
    projectCode: ref(Number(router.currentRoute.value.params.projectCode)),
    page: ref(1),
    name: ref(),
    limit: ref(10),
    searchVal: ref(),
    totalPage: ref(1),
    showRef: ref(false),
    startShowRef: ref(false),
    timingShowRef: ref(false),
    versionShowRef: ref(false),
    copyShowRef: ref(false),
    loadingRef: ref(false)
  })

  const createColumns = (variables: any) => {
    variables.columns = [
      // {
      //   type: 'selection',
      //   className: 'btn-selected',
      //   ...COLUMN_WIDTH_CONFIG['selection']
      // },
      {
        title: '#',
        key: 'id',
        width: '70',
        render: (row, index) => index + 1
      },
      {
        title: t('project.workflow.workflow_name'),
        key: 'name',
        className: 'workflow-name',
        ...COLUMN_WIDTH_CONFIG['name'],
        render: (row) =>
          h(
            NSpace,
            {
              justify: 'space-between',
              wrap: false,
              class: styles['workflow-name']
            },
            {
              default: () =>
                h(
                  ButtonLink,
                  {
                    onClick: () =>
                      void router.push({
                        name: 'workflow-definition-detail',
                        params: { code: row.code }
                      })
                  },
                  {
                    default: () =>
                      h(
                        NEllipsis,
                        COLUMN_WIDTH_CONFIG['linkEllipsis'],
                        () => row.name
                      )
                  }
                )
            }
          )
      },
      {
        title: t('project.workflow.description'),
        key: 'description',
        ...COLUMN_WIDTH_CONFIG['note']
      },
      // {
      //   title: 'Copy',
      //   key: 'copy',
      //   ...COLUMN_WIDTH_CONFIG['copy'],
      //   render: (row) =>
      //     h(
      //       NButton,
      //       {
      //         quaternary: true,
      //         circle: true,
      //         type: 'info',
      //         size: 'tiny',
      //         onClick: () => void copy(row.name)
      //       },
      //       { icon: () => h(NIcon, { size: 16 }, () => h(CopyOutlined)) }
      //     )
      // },
      {
        title: t('project.workflow.status'),
        key: 'releaseState',
        ...COLUMN_WIDTH_CONFIG['state'],
        render: (row) =>
          row.releaseState === 'ONLINE'
            ? t('project.workflow.up_line')
            : t('project.workflow.down_line')
      },
      {
        title: t('project.workflow.schedule_publish_status'),
        key: 'scheduleReleaseState',
        ...COLUMN_WIDTH_CONFIG['state'],
        render: (row) => {
          if (row.scheduleReleaseState === 'ONLINE') {
            return h(
              NTag,
              { type: 'success', size: 'small' },
              {
                default: () => t('project.workflow.up_line')
              }
            )
          } else if (row.scheduleReleaseState === 'OFFLINE') {
            return h(
              NTag,
              { type: 'warning', size: 'small' },
              {
                default: () => t('project.workflow.down_line')
              }
            )
          } else {
            return '-'
          }
        }
      },
      // {
      //   title: t('project.workflow.create_time'),
      //   key: 'createTime',
      //   ...COLUMN_WIDTH_CONFIG['time']
      // },
      // {
      //   title: t('project.workflow.update_time'),
      //   key: 'updateTime',
      //   ...COLUMN_WIDTH_CONFIG['time']
      // },
      // {
      //   title: t('project.workflow.create_user'),
      //   key: 'userName',
      //   ...COLUMN_WIDTH_CONFIG['userName']
      // },
      // {
      //   title: t('project.workflow.modify_user'),
      //   key: 'modifyBy',
      //   ...COLUMN_WIDTH_CONFIG['userName']
      // },
      {
        title: t('project.workpublish.owner'),
        key: 'owners',
        align: 'center',
        ...COLUMN_WIDTH_CONFIG['name'],
        render: (rowData: any, unused: number) =>
          h('div', null, [
            h('span', {}, rowData.owners.join(',')),
            h(
              NTooltip,
              { trigger: 'hover' },
              {
                trigger: () =>
                  h(
                    NButton,
                    {
                      circle: true,
                      type: 'info',
                      size: 'tiny',
                      style: { marginLeft: '5px' },
                      onClick: () => {
                        console.log('xxxx')
                      }
                    },
                    () => h(NIcon, null, () => h(EditOutlined))
                  ),
                default: () => t('project.workflow.editOwner')
              }
            )
          ])
      },
      {
        title: t('project.workflow.workflowcode'),
        key: 'code',
        width: 200,
        render: (row) =>   row.code
      },
      {
        title: t('project.workflow.operation'),
        key: 'operation',
        ...COLUMN_WIDTH_CONFIG['operation'](8),
        render: (row) =>
          h(TableAction, {
            row,
            onEditWorkflow: () => editWorkflow(row),
            onStartWorkflow: () => startWorkflow(row),
            onTimingWorkflow: () => timingWorkflow(row),
            onVersionWorkflow: () => versionWorkflow(row),
            onDeleteWorkflow: () => deleteWorkflow(row),
            onReleaseWorkflow: () => releaseWorkflow(row),
            onCopyWorkflow: () => copyWorkflow(row),
            onExportWorkflow: () => exportWorkflow(row),
            onGotoTimingManage: () => gotoTimingManage(row),
            onGotoWorkflowTree: () => gotoWorkflowTree(row)
          })
      }
    ] as TableColumns<any>
    if (variables.tableWidth) {
      variables.tableWidth = calculateTableWidth(variables.columns)
    }
  }

  const editWorkflow = (row: any) => {
    console.log('editWorkflow')
    variables.row = row
    // router.push({
    //   name: 'workflow-definition-detail',
    //   params: { code: row.code }
    // })
    router.push({
      path: '/projects/workflow/definitions/detail',
      query: {
        tab: `${t('project.workflow.create_workflow')}`,
        tabName: 'ProcessDefinedDetailTab',
        code: row.code 
      }
    })
  }

  const startWorkflow = (row: any) => {
    variables.startShowRef = true
    variables.row = row
  }

  const timingWorkflow = (row: any) => {
    variables.timingShowRef = true
    variables.row = row
  }
  // 显示版本弹窗
  const versionWorkflow = (row: any) => {
    variables.versionShowRef = true
    variables.row = row
  }
  
  // 删除作业流
  const deleteWorkflow = (row: any) => {
    deleteByCode({ deleteByCode :row.id } ).then(() => {
      getTableData({
        isTmp:false,
        name:variables.searchVal,
        limit: variables.limit,
        pageNo: variables.page,
      })
    })
  }

  const releaseWorkflow = (row: any) => {
    const data = {
      name: row.name,
      releaseState: (row.releaseState === 'ONLINE' ? 'OFFLINE' : 'ONLINE') as
        | 'OFFLINE'
        | 'ONLINE'
    }
    release({processId : row.id}).then(() => {
      getTableData({
        isTmp:false,
        name: variables.searchVal,
        limit: variables.limit,
        pageNo: variables.page,
        searchVal: variables.searchVal
      })
    })
  }

  const copyWorkflow = (row: any) => {
    const data = {
      codes: String(row.code),
      targetProjectCode: variables.projectCode
    }
    batchCopyByCodes({ processId : row.id}).then(() => {
      // window.$message.success(t('project.workflow.success'))
      getTableData({
        isTmp:false,
        name: variables.name,
        limit: variables.limit,
        pageNo: variables.page,
      })
    })
  }

  const downloadBlob = (data: any, fileNameS = 'json') => {
    if (!data) {
      return
    }
    const blob = new Blob([data])
    const fileName = `${fileNameS}.json`
    if ('download' in document.createElement('a')) {
      // Not IE
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      link.setAttribute('download', fileName)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link) // remove element after downloading is complete.
      window.URL.revokeObjectURL(url) // release blob object
    } else {
      // IE 10+
      if (window.navigator.msSaveBlob) {
        window.navigator.msSaveBlob(blob, fileName)
      }
    }
  }

  const exportWorkflow = (row: any) => {
    const fileName = 'workflow_' + new Date().getTime()

    const data = {
      codes: String(row.code)
    }
    batchExportByCodes(data, variables.projectCode).then((res: any) => {
      downloadBlob(res, fileName)
    })
  }

  const gotoTimingManage = (row: any) => {
    router.push({
      name: 'workflow-definition-timing',
      params: { projectCode: variables.projectCode, definitionCode: row.code }
    })
  }

  const gotoWorkflowTree = (row: any) => {
    router.push({
      name: 'workflow-definition-tree',
      params: { projectCode: variables.projectCode, definitionCode: row.code }
    })
  }

  const getTableData = (params: any) => {
    if (variables.loadingRef) return
    variables.loadingRef = true
    console.log('params',params)
    const { state } = useAsyncState(
      queryListPagingReq(params).then((res: any) => {
        variables.totalPage = 1
        variables.tableData = res.data.map((item: any) => {
          return { ...item }
        })
        variables.loadingRef = false
      }),
      { total: 0, table: [] }
    )
    return state
  }

  return {
    variables,
    createColumns,
    getTableData,
  }
}
